package top.xiaoazi.futureletterserver.module.letter.utils;

import lombok.SneakyThrows;
import top.xiaoazi.futureletterserver.FutureLetterServer;
import top.xiaoazi.futureletterserver.module.letter.service.LetterService;
import top.xiaoazi.futureletterserver.module.letter.vo.LetterSentVO;
import top.xiaoazi.futureletterserver.utils.CryptoAESUtils;

import java.util.TimerTask;


/**
 * 表示执行发送信件要做的任务，重写了run方法
 */
public class LetterTask extends TimerTask {

    private final LetterEmailUtils emailUtils = new LetterEmailUtils();

    // 要发送的信件内容
    private LetterSentVO letter;

    @SneakyThrows
    @Override
    public void run() {
        CryptoAESUtils cryptoAESUtils = FutureLetterServer.context.getBean(CryptoAESUtils.class);
        LetterService letterService = FutureLetterServer.context.getBean(LetterService.class);
        // 解密
        String title = cryptoAESUtils.decrypt(letter.getTitle());
        String htmlContent = cryptoAESUtils.decrypt(letter.getContent());
        String toEmail = letter.getToEmail();

        // 将这个 LetterTask 对象中的 data 给发送出去
        LetterSentVO sendLetter = new LetterSentVO();
        sendLetter.setTitle(title);
        sendLetter.setContent(htmlContent);
        sendLetter.setToEmail(toEmail);
        sendLetter.setEmail(letter.getEmail());
        sendLetter.setUsername(letter.getUsername());
        emailUtils.send(sendLetter); // 发邮件

        // 发送完成后, 将信件改成已经发送的状态
        this.letter.setState(1);
        letterService.setState(this.letter);
    }

    public LetterTask() {
    }

    public LetterTask(LetterSentVO letter) {
        this.letter = letter;
    }

    public void setLetter(LetterSentVO letter) {
        this.letter = letter;
    }
}